package com.example.mydy;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.example.mydy.adapter.TaskHistoryAdapter;
import com.example.mydy.model.Task;
import com.example.mydy.model.UserInfo;
import com.example.mydy.utils.ImageUtils;
import com.example.mydy.utils.MockDataManager;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.tabs.TabLayout;

import java.util.ArrayList;
import java.util.List;

public class MyTasksActivity extends AppCompatActivity implements TaskHistoryAdapter.OnTaskClickListener {

    private static final String TAG = "MyTasksActivity";
    
    private ImageButton backButton;
    private TabLayout tabLayout;
    private SwipeRefreshLayout swipeRefreshLayout;
    private RecyclerView taskListRecycler;
    private FloatingActionButton fabAddTask;
    
    private MockDataManager mockDataManager;
    private UserInfo currentUser;
    private List<Task> taskList;
    private TaskHistoryAdapter taskAdapter;
    
    private int currentTab = 0; // 0:全部, 1:待审核, 2:已通过, 3:已拒绝
    private long highlightTaskId = -1; // 高亮显示的任务ID，-1表示不高亮
    
    // 使用Activity Result API启动提交任务页面并处理返回结果
    private final ActivityResultLauncher<Intent> submitTaskLauncher = 
        registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), 
            result -> {
                if (result.getResultCode() == RESULT_OK && result.getData() != null) {
                    // 获取新提交任务的ID
                    highlightTaskId = result.getData().getLongExtra("taskId", -1);
                    
                    // 刷新任务列表，显示新提交的任务
                    loadTasks();
                }
            });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_tasks);
        
        // 初始化数据管理器
        mockDataManager = MockDataManager.getInstance();
        currentUser = mockDataManager.getCurrentUser();
        
        if (currentUser == null) {
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        
        // 检查是否有需要高亮显示的任务ID
        if (getIntent().hasExtra("taskId")) {
            highlightTaskId = getIntent().getLongExtra("taskId", -1);
        }
        
        // 初始化视图
        initViews();
        setupListeners();
        setupTabLayout();
        
        // 初始化任务列表
        initTaskList();
        
        // 加载任务列表
        loadTasks();
    }
    
    private void initViews() {
        backButton = findViewById(R.id.btn_back);
        tabLayout = findViewById(R.id.tab_layout);
        swipeRefreshLayout = findViewById(R.id.swipe_refresh_layout);
        taskListRecycler = findViewById(R.id.task_list_recycler);
        fabAddTask = findViewById(R.id.fab_add_task);
    }
    
    private void setupListeners() {
        // 返回按钮
        backButton.setOnClickListener(v -> onBackPressed());
        
        // 下拉刷新
        swipeRefreshLayout.setOnRefreshListener(this::loadTasks);
        
        // 添加任务按钮 - 使用ActivityResultLauncher启动任务提交页面
        fabAddTask.setOnClickListener(v -> {
            Intent intent = new Intent(MyTasksActivity.this, SubmitTaskActivity.class);
            submitTaskLauncher.launch(intent);
        });
    }
    
    private void setupTabLayout() {
        // 添加标签页
        tabLayout.addTab(tabLayout.newTab().setText("全部"));
        tabLayout.addTab(tabLayout.newTab().setText("待审核"));
        tabLayout.addTab(tabLayout.newTab().setText("已通过"));
        tabLayout.addTab(tabLayout.newTab().setText("已拒绝"));
        
        // 设置选择监听器
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                currentTab = tab.getPosition();
                filterTasks();
            }
            
            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                // 不需要处理
            }
            
            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                // 不需要处理
            }
        });
    }
    
    private void initTaskList() {
        taskList = new ArrayList<>();
        taskAdapter = new TaskHistoryAdapter(this, taskList, this);
        
        taskListRecycler.setLayoutManager(new LinearLayoutManager(this));
        taskListRecycler.setAdapter(taskAdapter);
    }
    
    private void loadTasks() {
        // 开始刷新动画
        swipeRefreshLayout.setRefreshing(true);
        
        if (currentUser != null) {
            // 清空当前列表
            taskList.clear();
            
            // 获取用户的所有任务
            List<Task> userTasks = MockDataManager.getUserTasks(currentUser.getUsername());
            if (userTasks != null && !userTasks.isEmpty()) {
                taskList.addAll(userTasks);
                
                // 根据当前标签页过滤任务
                filterTasks();
            } else {
                // 如果没有任务，也需要通知适配器更新
                taskAdapter.notifyDataSetChanged();
            }
        }
        
        // 结束刷新动画
        swipeRefreshLayout.setRefreshing(false);
    }
    
    private void filterTasks() {
        List<Task> filteredList = new ArrayList<>();
        
        for (Task task : taskList) {
            boolean shouldAdd = false;
            
            switch (currentTab) {
                case 0: // 全部
                    shouldAdd = true;
                    break;
                case 1: // 待审核
                    shouldAdd = task.isPending();
                    break;
                case 2: // 已通过
                    shouldAdd = task.isApproved();
                    break;
                case 3: // 已拒绝
                    shouldAdd = task.isRejected();
                    break;
            }
            
            if (shouldAdd) {
                filteredList.add(task);
            }
        }
        
        // 更新适配器数据
        taskAdapter.updateTasks(filteredList);
        
        // 如果有需要高亮的任务，找到它并滚动到该位置
        if (highlightTaskId > 0) {
            for (int i = 0; i < filteredList.size(); i++) {
                if (filteredList.get(i).getId() == highlightTaskId) {
                    taskListRecycler.scrollToPosition(i);
                    // 只高亮一次
                    highlightTaskId = -1;
                    break;
                }
            }
        }
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        // 每次恢复时刷新任务列表
        loadTasks();
    }
    
    @Override
    public void onTaskClick(Task task) {
        // 显示任务详情对话框
        showTaskDetailDialog(task);
    }
    
    private void showTaskDetailDialog(Task task) {
        final Dialog dialog = new Dialog(this);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.dialog_task_detail);
        
        TextView titleView = dialog.findViewById(R.id.tv_detail_title);
        TextView timeView = dialog.findViewById(R.id.tv_detail_time);
        TextView statusView = dialog.findViewById(R.id.tv_detail_status);
        TextView descriptionView = dialog.findViewById(R.id.tv_detail_description);
        ImageView imageView = dialog.findViewById(R.id.iv_detail_image);
        LinearLayout rejectionLayout = dialog.findViewById(R.id.layout_rejection);
        TextView rejectReasonView = dialog.findViewById(R.id.tv_reject_reason);
        Button closeButton = dialog.findViewById(R.id.btn_close_detail);
        
        // 设置任务详情
        titleView.setText(task.getTitle());
        timeView.setText("提交时间：" + task.getSubmittedAt());
        descriptionView.setText(task.getDescription());
        
        // 根据任务状态设置不同的状态显示
        if (task.isPending()) {
            statusView.setText("待审核");
            statusView.setBackgroundResource(R.drawable.bg_status_pending);
            rejectionLayout.setVisibility(View.GONE);
        } else if (task.isApproved()) {
            statusView.setText("已通过");
            statusView.setBackgroundResource(R.drawable.bg_status_approved);
            rejectionLayout.setVisibility(View.GONE);
        } else if (task.isRejected()) {
            statusView.setText("已拒绝");
            statusView.setBackgroundResource(R.drawable.bg_status_rejected);
            rejectionLayout.setVisibility(View.VISIBLE);
            
            // 显示拒绝原因
            String rejectReason = task.getRejectReason();
            if (rejectReason != null && !rejectReason.isEmpty()) {
                rejectReasonView.setText(rejectReason);
            } else {
                rejectReasonView.setText("暂无拒绝原因");
            }
        }
        
        // 加载任务图片
        String imageUrl = task.getImageUrl();
        if (imageUrl != null && !imageUrl.isEmpty()) {
            try {
                Bitmap bitmap = ImageUtils.loadImageFromStorage(this, imageUrl);
                if (bitmap != null) {
                    imageView.setImageBitmap(bitmap);
                }
            } catch (Exception e) {
                Log.e(TAG, "加载任务图片失败: " + e.getMessage());
                imageView.setImageResource(android.R.drawable.ic_menu_gallery);
            }
        } else {
            imageView.setImageResource(android.R.drawable.ic_menu_gallery);
        }
        
        // 设置关闭按钮
        closeButton.setOnClickListener(v -> dialog.dismiss());
        
        dialog.show();
    }
} 